//
//  AddNewFriendPacketCenter.m
//  HiQServer
//
//  Created by shoguncao on 12-8-11.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AddNewFriendPacketCenter.h"
#import "BuddyListPacketCenter.h"
#import "MacroComd.h"
#import "MysqlDB.h"
#import "MiniSocket.h"
#import "MainSocketDelegate.h"

@implementation AddNewFriendPacketCenter

- (void)MessageDispatch: (SockPacket *)packet
{
    UTF8Char * bytes = (UTF8Char *)[packet.packetContent bytes];
    NSUInteger operation = *((NSUInteger *)(bytes+8));
    
    GCDAsyncSocket *socket = packet.subAsynSocket;
    
    switch (operation) 
    {
        case OP_SEARCH_NEW_FRIEND:
        {
            NSInteger userId = *((NSUInteger *)(bytes+16));
            [self searchForUser:userId socket:socket];
            break;
        }
            
        case OP_ADD_REQUEST:
        {
            NSInteger fromId = *((NSUInteger *)(bytes+16));
            NSInteger toId = *((NSUInteger *)(bytes+24));
            [self onSendAddNewFriendRequest:fromId to:toId socket:socket];
            break;
        }
            
        case OP_ADD_REPLY:
        {
            NSInteger fromId = *((NSUInteger *)(bytes+16));
            NSInteger toId = *((NSUInteger *)(bytes+24));
            NSInteger isAccept = *((NSUInteger *)(bytes+32));
            [self sendAddFriendReply:isAccept fromId:fromId toId:toId];
        }
            
        default:
            break;
    }
}

- (void)searchForUser:(NSInteger)userId socket:(GCDAsyncSocket *)socket
{
    MysqlDB *mysql = [[MysqlDB alloc] init];
    [mysql connectHost:hostIp connectUser:userName connectPassword:password connectName:dbName];
    
    NSString *sqlCmd = [NSString stringWithFormat:@"SELECT * FROM tbUser WHERE UserID = %ld", userId];
    NSMutableArray *userArray = [mysql doDataQuery:sqlCmd];
    
    if ([userArray count] == 0)
    {
        NSInteger packetLen = 3 * sizeof(NSInteger);
        char *packet = NewPtr(packetLen);
        char *ptr = packet;
        *((NSInteger *)ptr) = CMD_FUN_ADD_NEW_FRIEND;   // 主功能号
        ptr = ptr + sizeof(NSInteger);
        *((NSInteger *)ptr) = OP_SEARCH_NEW_FRIEND;   // 次功能号
        ptr = ptr + sizeof(NSInteger);
        *((NSInteger *)ptr) = 0;    // userInfo 信息长度(因未找到，所以长度为 0)
        
        NSMutableData *sendData = [[NSMutableData alloc] initWithBytes:&packetLen length:sizeof(packetLen)];
        [sendData appendBytes:packet length:packetLen];
        [socket writeData:sendData withTimeout:-1 tag:0];
        
        DisposePtr(packet);
    }
    else
    {
        NSMutableArray *userInfo = [userArray objectAtIndex:0];
        NSData *userInfoData = [NSKeyedArchiver archivedDataWithRootObject:userInfo];
        
        NSInteger packetLen = 3 * sizeof(NSInteger) + [userInfoData length];
        char *packet = NewPtr(packetLen);
        char *ptr = packet;
        *((NSInteger *)ptr) = CMD_FUN_ADD_NEW_FRIEND;   // 主功能号
        ptr = ptr + sizeof(NSInteger);
        *((NSInteger *)ptr) = OP_SEARCH_NEW_FRIEND;   // 次功能号
        ptr = ptr + sizeof(NSInteger);
        *((NSInteger *)ptr) = [userInfoData length];    // userInfo 信息长度
        ptr = ptr + sizeof(NSInteger);
        [userInfoData getBytes:ptr length:[userInfoData length]];   // userInfo
        
        NSMutableData *sendData = [[NSMutableData alloc] initWithBytes:&packetLen length:sizeof(packetLen)];
        [sendData appendBytes:packet length:packetLen];
        [socket writeData:sendData withTimeout:-1 tag:0];
        
        DisposePtr(packet);
    }
    
    [mysql disconnect];
}

- (void)onSendAddNewFriendRequest:(NSInteger)fromId to:(NSInteger)toId socket:(GCDAsyncSocket *)socket
{
    MiniSocket *sock = [self isBuddyOnline:toId];
    if (sock == nil)    // 要添加的好友不在线
    {
        NSInteger packetLen = 5 * sizeof(NSInteger);
        char *packet = NewPtr(packetLen);
        char *ptr = packet;
        *((NSInteger *)ptr) = CMD_FUN_ADD_NEW_FRIEND;   // 主功能号
        ptr = ptr + sizeof(NSInteger);
        *((NSInteger *)ptr) = OP_ADD_REPLY;   // 次功能号
        ptr = ptr + sizeof(NSInteger);
        *((NSInteger *)ptr) = fromId;
        ptr = ptr + sizeof(NSInteger);
        *((NSInteger *)ptr) = toId;
        ptr = ptr + sizeof(NSInteger);
        *((NSInteger *)ptr) = REPLY_OFFLINE;
        
        NSMutableData *sendData = [[NSMutableData alloc] initWithBytes:&packetLen length:sizeof(packetLen)];
        [sendData appendBytes:packet length:packetLen];
        [socket writeData:sendData withTimeout:-1 tag:0];
        
        DisposePtr(packet);
    }
    else    // 要添加的好友在线，向好友发送添加好友请求
    {
        NSInteger packetLen = 4 *sizeof(NSInteger);
        char *packet = NewPtr(packetLen);
        char *ptr = packet;
        *((NSInteger *)ptr) = CMD_FUN_ADD_NEW_FRIEND;   // 主功能号
        ptr = ptr + sizeof(NSInteger);
        *((NSInteger *)ptr) = OP_ADD_REQUEST;   // 次功能号
        ptr = ptr + sizeof(NSInteger);
        *((NSInteger *)ptr) = fromId;    // 发请求的用户
        ptr = ptr + sizeof(NSInteger);
        *((NSInteger *)ptr) = toId;    // 被请求的用户
        
        NSMutableData *sendData = [[NSMutableData alloc] initWithBytes:&packetLen length:sizeof(packetLen)];
        [sendData appendBytes:packet length:packetLen];
        [sock.miniAsynSocket writeData:sendData withTimeout:-1 tag:0];
        
        DisposePtr(packet);
    }
}

- (void)sendAddFriendReply:(NSInteger)isAccept fromId:(NSInteger)fromId toId:(NSInteger)toId
{
    MiniSocket *sock = [self isBuddyOnline:fromId];
    
    if (sock == nil)
        return;
    
    if (isAccept == REPLY_ACCEPT)
    {
        MysqlDB *mysql = [[MysqlDB alloc] init];
        [mysql connectHost:hostIp connectUser:userName connectPassword:password connectName:dbName];
        
        NSString *sqlCmd;
        NSMutableArray *sqlResult;
        
        sqlCmd = [NSString stringWithFormat:@"SELECT * FROM tbFriends WHERE UserId=%ld AND FriendId=%ld;", fromId, toId];
        sqlResult = [mysql doDataQuery:sqlCmd];
        if ([sqlResult count] <= 0)
        {
            sqlCmd = [NSString stringWithFormat:@"INSERT INTO tbFriends VALUES ('0', '%ld', '%ld', '', '', '')", fromId, toId];
            [mysql doDataInsert:sqlCmd];
        }
        
        sqlCmd = [NSString stringWithFormat:@"SELECT * FROM tbFriends WHERE UserId=%ld AND FriendId=%ld;", toId, fromId];
        sqlResult = [mysql doDataQuery:sqlCmd];
        if ([sqlResult count] <= 0)
        {
            sqlCmd = [NSString stringWithFormat:@"INSERT INTO tbFriends VALUES ('0', '%ld', '%ld', '', '', '')", toId, fromId];
            [mysql doDataInsert:sqlCmd];
        }

        [mysql disconnect];
        
        // 向 fromId 发好友列表
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        NSNumber *fromIdNum = [NSNumber numberWithInt:fromId];
        GCDAsyncSocket *fromSocket = [sock miniAsynSocket];
        [dic setValue:fromIdNum forKey:@"qqNum"];
        [dic setValue:fromSocket forKey:@"socket"];
        [[NSNotificationCenter defaultCenter] postNotificationName:Notify_Send_BuddyList object:self userInfo:dic];
        
        // 向 toId 发好友列表
        MiniSocket *socket = [self isBuddyOnline:toId];
        if (socket != nil)
        {
            dic = [[NSMutableDictionary alloc] init];
            NSNumber *toIdNum = [NSNumber numberWithInt:toId];
            GCDAsyncSocket *toSocket = [socket miniAsynSocket];
            [dic setValue:toIdNum forKey:@"qqNum"];
            [dic setValue:toSocket forKey:@"socket"];
            [[NSNotificationCenter defaultCenter] postNotificationName:Notify_Send_BuddyList object:self userInfo:dic];
        }
    }

    NSInteger packetLen = 5 * sizeof(NSInteger);
    char *packet = NewPtr(packetLen);
    char *ptr = packet;
    *((NSInteger *)ptr) = CMD_FUN_ADD_NEW_FRIEND;   // 主功能号
    ptr = ptr + sizeof(NSInteger);
    *((NSInteger *)ptr) = OP_ADD_REPLY;   // 次功能号
    ptr = ptr + sizeof(NSInteger);
    *((NSInteger *)ptr) = fromId;
    ptr = ptr + sizeof(NSInteger);
    *((NSInteger *)ptr) = toId;
    ptr = ptr + sizeof(NSInteger);
    *((NSInteger *)ptr) = isAccept;

    NSMutableData *sendData = [[NSMutableData alloc] initWithBytes:&packetLen length:sizeof(packetLen)];
    [sendData appendBytes:packet length:packetLen];
    [sock.miniAsynSocket writeData:sendData withTimeout:-1 tag:0];

    DisposePtr(packet);
}

// 判断 userId 对应的用户是否在线
- (MiniSocket *)isBuddyOnline:(NSInteger)userId
{
    @synchronized([MainSocketDelegate connectedSocketsQueue])
    {
        // 遍历 connectedSocketQueue，找到该好友的 _sock
        for (MiniSocket *_sock in [MainSocketDelegate connectedSocketsQueue]) 
        {
            if (_sock.userId == userId)
            {
                return _sock;
            }
        }
        return nil;
    }
}

@end
